import {defineStore} from "pinia";
import {AuthLoginR} from "@/api/auth";
import {ElMessage} from "element-plus";
import {LoginRequest} from "@/interface/auth";
import {useRouter} from "vue-router";

const router = useRouter()

//创建store
const useUserStore = defineStore('user', {
  // 定义状态：一个函数，返回一个对象
  state: () => {
    return {
      username: '',
      mobile: '',
      token: '',
      exp: 0
    }
  },

  //定义getters，等同于组件的计算属性
  getters: {
    //getter 函数接收 state 作为参数，推荐使用箭头函数
    isLogin: state => !!state.token
  },

  //定义actions，有同步和异步两种类型
  actions: {
    //异步 action，一般用来处理异步逻辑
    async login(req: LoginRequest) {
      this.logout()
      await AuthLoginR(req).then(res => {
        return res.data
      }).then(res => {
        switch (res.code) {
          case 200:
            this.mobile = res.data.mobile
            this.token = res.data.token
            this.exp = res.data.exp
            this.username = req.name.trim()
            // ElMessage.success('登录成功')

            break
          default:
        }
      }).catch(err => {
        ElMessage.error('登录请求失败:' + err.toString())
      })
    },

    //同步action
    logout() {
      this.token = ''
      this.username = ''
      this.mobile = ''
      this.exp = 0
    }
  }
})

export default useUserStore